<template>
  <el-dialog
      v-model="visible"
      title="调拨明细"
      :width="'80%'"
      @close="handleClose"
      :before-close="handleBeforeClose"
      :modal="true"
      custom-class="dialog-with-scroll"
  >
    <template #header>
      <el-row :gutter="20" type="flex" justify="start">
        <el-col :span="6">
          <el-input
              v-model="filters.rawProductName"
              placeholder="物品名称"
              clearable
              size="small"
          />
        </el-col>
        <el-col :span="6">
          <el-input
              v-model="filters.rawProductBatch"
              placeholder="物品批次"
              clearable
              size="small"
          />
        </el-col>
        <el-col :span="6">
          <el-input
              v-model="filters.origin"
              placeholder="起源地"
              clearable
              size="small"
          />
        </el-col>
        <el-col :span="6">
          <el-button
              type="primary"
              size="small"
              @click="applyFilters"
              style="margin-top: 4px;"
          >
            查询
          </el-button>
          <el-button
              type="primary"
              size="small"
              @click="resetFilters"
              style="margin-top: 4px;"
          >
            重置
          </el-button>
        </el-col>
      </el-row>
    </template>

    <template #default>
      <div v-if="groupedDetails.length" class="total-quantity">
        <p><strong>总数量:</strong> {{ groupedDetails.length }} 条</p>
      </div>
      <el-table
          v-if="groupedDetails.length"
          :data="currentGroupedDetails"  style="width: 100%"
          border
      >
        <el-table-column label="详情" min-width="500">
          <template #default="props">
            <div class="desc-box">
              <el-descriptions :column="7" class="desc-box" v-for="(item, index) in props.row.items" :key="index">
                <el-descriptions-item label="调拨明细编码:" width="65">{{ item.allocationDetailNo }}</el-descriptions-item>
                <el-descriptions-item label="货品重量:" width="50">{{ item.weight.toFixed(2) }}{{ item.weightUnit }}</el-descriptions-item>
                <el-descriptions-item label="物品批次:" width="50">{{ props.row.rawProductBatch }}</el-descriptions-item>
                <el-descriptions-item label="物品名称:" width="45">{{ props.row.rawProductName }}</el-descriptions-item>
                <el-descriptions-item label="数量:" width="45">{{ item.transportQuantity }}</el-descriptions-item>
                <el-descriptions-item label="起源地:" width="50">{{ props.row.origin }}</el-descriptions-item>
                <el-descriptions-item label="是否送达:" width="50">{{ item.status }}</el-descriptions-item>
              </el-descriptions>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div v-else>
        <el-alert
            title="未找到相关调拨明细"
            type="info"
            description="当前调拨暂无明细数据"
            show-icon
        />
      </div>
    </template>
    <template #footer>
      <el-button @click="visible = false">关闭</el-button>
      <el-pagination
          v-if="groupedDetails.length > 0"
          :page-size="pageSize"
          :total="groupedDetails.length"
          :current-page="currentPage"
          @current-change="handlePageChange"
          layout="prev, pager, next, jumper"
      />
    </template>
  </el-dialog>
</template>

<script>
import { ref, onMounted, watch } from 'vue';
import { getAllocationDetail } from '@/api/delivery/allocation.js';
import { ElMessage } from 'element-plus';

export default {
  props: {
    modelValue: {
      type: Boolean,
      required: true
    },
    order: {
      type: String,
      required: true
    }
  },
  setup(props, { emit }) {
    const visible = ref(props.modelValue);
    const details = ref([]);
    const pageSize = 10; // 每页显示的条数
    const currentPage = ref(1); // 当前页码
    const currentGroupedDetails = ref([]); // 当前页显示的详情
    const groupedDetails = ref([]); // 分组后的详情

    const updateCurrentGroupedDetails = () => {
      const startIndex = (currentPage.value - 1) * pageSize;
      const endIndex = startIndex + pageSize;
      currentGroupedDetails.value = groupedDetails.value.slice(startIndex, endIndex);
    };

    const handlePageChange = (page) => {
      currentPage.value = page;
      updateCurrentGroupedDetails();
    };

    const formatDate = (value) => {
      if (!value) return '';
      const date = new Date(value);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    };

    const filteredDetails = ref([]);
    const filters = ref({
      rawProductName: '',
      rawProductBatch: '',
      origin: ''
    });

    const applyFilters = () => {
      filteredDetails.value = details.value.filter(detail => {
        return (
            (!filters.value.rawProductName || detail.rawProductName.includes(filters.value.rawProductName)) &&
            (!filters.value.rawProductBatch || detail.rawProductBatch.includes(filters.value.rawProductBatch)) &&
            (!filters.value.origin || detail.origin.includes(filters.value.origin))
        );
      });
      groupDetails(filteredDetails.value);
    };

    const resetFilters = () => {
      filters.value = {
        rawProductName: '',
        rawProductBatch: '',
        origin: ''
      };
      applyFilters();
    };

    const groupDetails = (details) => {
      const grouped = {};
      details.forEach(detail => {
        if (!grouped[detail.rawProductBatch]) {
          grouped[detail.rawProductBatch] = {
            rawProductBatch: detail.rawProductBatch,
            rawProductName: detail.rawProductName,
            origin: detail.origin,
            items: []
          };
        }
        grouped[detail.rawProductBatch].items.push(detail);
      });
      groupedDetails.value = Object.values(grouped);
      updateCurrentGroupedDetails();
    };

    const fetchDetails = async () => {
      try {
        console.log('Fetching details for order:', props.order);
        const response = await getAllocationDetail(props.order);
        details.value = response.data || [];
        console.log(details.value);
        applyFilters();
      } catch (error) {
        ElMessage.error('获取调拨明细失败');
        console.error(error);
      }
    };

    const handleBeforeClose = (done) => {
      emit('update:modelValue', false); // 关闭时触发更新父组件的状态
      done();
    };

    const handleClose = () => {
      visible.value = false;
    };

    watch(() => props.modelValue, (newVal) => {
      if (newVal) {
        fetchDetails();
      }
    });

    onMounted(() => {
      if (props.modelValue) {
        fetchDetails();
      }
    });

    watch(() => props.modelValue, (newVal) => {
      visible.value = newVal;
      if (newVal) {
        fetchDetails();
      }
    });

    return {
      visible,
      details,
      currentGroupedDetails,
      pageSize,
      currentPage,
      formatDate,
      handleClose,
      handleBeforeClose,
      handlePageChange,
      applyFilters,
      filteredDetails,
      filters,
      resetFilters,
      groupedDetails
    };
  }
};
</script>

<style scoped>
.total-quantity {
  margin-bottom: 10px;
}

.el-pagination {
  margin-top: 10px;
}

.dialog-with-scroll .el-dialog__body {
  max-height: 400px;  /* 设置最大高度 */
  overflow-y: auto;   /* 允许纵向滚动 */
}

.sub-row {
  margin-bottom: 10px;
}

.desc-box {
  margin-left: 20px;
}

.el-table {
  display: flex;
  flex-direction: column;
}

.el-table__body-wrapper {
  flex: 1;
}

.el-table__header-wrapper {
  flex: 0 0 auto;
}
</style>
